package br.ufu.si.view;

import java.awt.Component;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Set;

import javax.swing.JComponent;
import javax.swing.text.JTextComponent;

import br.ufu.si.util.ReflectionUtil;

public abstract class AbstractBeanField  implements BeanField{
	
	protected HashMap<String, JComponent> beanFields;
	protected Object bean;
	
	public AbstractBeanField() {
		beanFields = new HashMap<String, JComponent>();
		setBean();
	}
	
	@Override
	public HashMap<String, JComponent> getBeanFields() {
		if (beanFields == null) {
			beanFields = new HashMap<String, JComponent>();
		}
		return beanFields;
	}
	
	public Object getJComponentValue(Component component){
		if(component instanceof JTextComponent){
			return ((JTextComponent) component).getText();
		}
		return null;
	}
	
	public Object getBean(){
		
		Set<String> fieldsName = beanFields.keySet();
		
		for(String fieldName:fieldsName){
			
			String setter = ReflectionUtil.buildSetMethodName(fieldName);

			try {

				Field field = bean.getClass().getDeclaredField(fieldName);
				Method method = bean.getClass().getMethod(setter, field.getType());
				
				method.invoke(bean, getJComponentValue(beanFields.get(fieldName)));
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		
		}
		return bean;
	}

}
